<template>
    <div class='container'>
        <div class="header">
            <div class="back"> <t-button @click="safeGoBack">返回</t-button></div>
            <div class="title">{{ title }} 当前文章 ID：{{ id }}
            </div>
        </div>

        <div class="description">
            <div class="tag">
                <div class="item"><t-tag>前端</t-tag></div>
                <div class="item"><t-tag>后端</t-tag></div>
                <div class="item"><t-tag>数据库</t-tag></div>
            </div>
            <div class="author">张三</div>
            <div class="update">最后修改时间 2025-01-01 12:00:00</div>
        </div>
        <div class="readonly">
            <MdPreview :editorId="doc_id" :modelValue="preview_text" class="content" />
            <MdCatalog :editorId="doc_id" :scrollElement="scrollElement" class="catalog" />
        </div>
    </div>
</template>
<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router'
import { onMounted, ref } from 'vue'
import { MdPreview, MdCatalog } from 'md-editor-v3';
const doc_id = 'preview-only';
const title = ref("契约锁电子签章系统 pdfverifier 远程代码执行漏洞分析（补丁包逆向分析）")
const preview_text = ref()
const content = ref(`![图片](https://mmbiz.qpic.cn/sz_mmbiz_png/8208GibianvzL44qTW6v7uyVCPkECxXb5JUwkgHxzrz9NlFEntc1O6HmJTCZA3aXMlh4tKzN5gianBQvems5OANqA/640?wx_fmt=png&from=appmsg&randomid=4iiu659n&watermark=1&tp=webp&wxfrom=5&wx_lazy=1)`);

const scrollElement = document.documentElement;
const route = useRoute()
const id = route.params.id
onMounted(() => {
    console.log('当前详情ID:', id)
    // 根据 id 请求数据
})

const router = useRouter()

const safeGoBack = () => {
    // 如果有上一页，就返回；否则跳转到默认页面（如列表页）
    if (window.history.length > 1) {
        router.go(-1)
    } else {
        router.push('/blog') // 假设列表页路径是 /blog
    }
}


function addHeadingNumbers(markdown: string): string {
    const lines = markdown.split('\n');
    const headingLevels: number[] = [0, 0, 0, 0, 0, 0]; // 最多支持6级标题

    return lines
        .map((line) => {
            const headingMatch = line.match(/^#+/);
            if (!headingMatch) return line;

            const level = headingMatch[0].length - 1; // 一级标题 level = 0
            const rest = line.slice(level + 1).trim();

            // 清除比当前 level 深的层级
            for (let i = level + 1; i < headingLevels.length; i++) {
                headingLevels[i] = 0;
            }

            // 当前层级编号 +1
            headingLevels[level] += 1;

            // 构造序号，从第一个非零值开始
            const path = headingLevels.slice(0, level + 1);
            const startIndex = path.findIndex((n) => n > 0);
            const numberPrefix = path
                .slice(startIndex, level + 1)
                .join('.')
                .replace(/^0/, '1'); // 防止从 0 开始（比如第一个标题是三级）

            return `${'#'.repeat(level + 1)} ${numberPrefix}. ${rest}`;
        })
        .join('\n');
}

onMounted(() => {
    preview_text.value = addHeadingNumbers(content.value)
})
</script>
<style lang='scss' scoped>
.content img {
    width: 200px !important;
    height: auto;
}

.container {
    width: 90%;
    margin: 0 auto;
}

.header {
    margin: 10px 0;
    display: flex;
    gap: 10px;
    justify-content: flex-start;
    align-items: center;

    .back {
        color: aqua;
    }

    .title {
        font-weight: 600;
    }

}

.description {

    display: flex;
    justify-content: flex-start;

    .tag {
        display: inline-flex;
        gap: 2px;
    }
}

.readonly {
    display: flex;
    width: 100%;
    margin: 0 auto;
    justify-content: flex-start;

    .content {
        width: 90%;
    }

    .catalog {
        margin-left: 20px;
        position: sticky; // 关键：让 catalog 在滚动时“粘”在某个位置
        top: 200px; // 关键：距离视口顶部 100px 开始固定
        align-self: start; // 防止父元素对齐影响 sticky 行为
        height: fit-content; // 可选：避免内容被截断

    }
}
</style>